
//
//  AllCommentViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/3/6.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import SnapKit
import PKHUD

class AllCommentViewController: BaseViewController, BottomShadow, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet weak var mainTableView: UITableView!
    private let headerViewHeight: CGFloat = 45
    private let contentButtonHeight: CGFloat = 35
    private let LRMargin: CGFloat = 10
    
    var contentBtn: UIButton?
    var praiseRate:String=""
    var page:Int = 0
    var totalPage:Int = 0
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    
    var commodityModel: GoodsModel!
    var commentData:[GoodsCommentModel]=[]
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        // Do any additional setup after loading the view.
    }
    
    
    
    func setUI() {
        
        titleLabel(text: "蜜友评价", nil)
        mainTableView.register(UINib(nibName: "\(ShoppingCommentTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "cell")
        mainTableView.estimatedRowHeight = 100
        mainTableView.rowHeight = UITableViewAutomaticDimension
        let footerAction:Selector = #selector(footerRefresh)
        footer.setRefreshingTarget(self, refreshingAction: footerAction)
        mainTableView.mj_footer = footer
        mainTableView.mj_footer.isHidden = true
        footerRefresh()
    }
    
    // 底部刷新
    @objc func footerRefresh(){
        print("上拉刷新")
        page += 1
        self.fetchProductCommentList(parameters: ["page":page,"pageSize":10,"goodId":commodityModel.id!])
    }
    
    func setHeaderView() -> UIView {
        let headerView = UIView()
        headerView.backgroundColor = ONColor.cellBGColor
        headerView.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: headerViewHeight)
        let contentButton = UIButton(type: .custom)
        contentButton.setTitle("推荐指数\(self.praiseRate)", for: .normal)
        contentButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        contentButton.setTitleColor(UIColor.black, for: .normal)
        contentButton.frame = CGRect(x: LRMargin, y: 0, width: headerView.width - LRMargin * 2, height: contentButtonHeight)
        contentButton.isUserInteractionEnabled = false
        contentButton.backgroundColor = UIColor.white
        headerView.addSubview(contentButton)
        contentBtn = contentButton
        setShadow(view: contentButton, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)
        return headerView
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.commentData.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? ShoppingCommentTableViewCell
        let model = commentData[indexPath.section]
        cell?.showData(model: model)
        return cell!
    }
    
    
    /// 获取商品列表评论数据
    func fetchProductCommentList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(goodsCommentListUrl)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let arr = json["data"]["rows"].array!
                                        self.totalPage = json["data"]["total"].int!
                                        self.praiseRate = json["data"]["praiseRate"].string!
                                        
                                        if self.page == 1 {
                                            self.mainTableView.tableHeaderView = self.setHeaderView()
                                        }
                                        
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            
                                            var model = GoodsCommentModel(fromDic: dic)
                                            if let pic = dic["pics"]{
                                                let pics = pic.array!
                                                
                                                model.initPics(arr: pics)
                                            }
                                            
                                            let author = dic["commentUser"]
                                            if !(author?.isEmpty)!{
                                                model.initAuthor(dic: (author?.dictionary!)!)
                                            }
                                            let arr = dic["relatedComments"]?.array
                                            model.relatedCommentsCount = "\(arr?.count)"
                                            
                                            self.commentData.append(model)
                                        }
                                        
                                        self.titleLabel(text: "蜜友评价(\(self.commentData.count))", nil)
                                        if self.totalPage == self.commentData.count{
                                            self.mainTableView.mj_footer.isHidden = true
                                        }
                                        else{
                                            self.mainTableView.mj_footer.isHidden = false
                                        }
                                        print(self.commentData)
                                        self.mainTableView.reloadData()
                                    }
                                    else{
                                        
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }
}

